﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace JobCreateInDocs_DLL
{
    public static class KoEnvironment
    {
        #region Members
        private static string _AxaptaConnStr = "";
        public static string AxaptaConnStr
        {
            get
            {
                /*
  <appSettings>
    <add key="AXAPTAConnect" value="Provider=SQLOLEDB;Data Source=DBSrv;Initial Catalog=DBName;User id=UserName;Password=Pwd;" />
  </appSettings>
</configuration>
                 */
                _AxaptaConnStr = GetAppSetting(@"AXAPTAConnect");
                return KoEnvironment._AxaptaConnStr;
            }
        }
        private static string _DB04ConnStr = "";
        public static string DB04ConnStr
        {
            get
            {
                _DB04ConnStr = GetAppSetting(@"DB04Connect");
                return KoEnvironment._DB04ConnStr;
            }
        }
        private static string _DBMySQLMainConnStr = "";
        public static string DBMySQLMainConnStr
        {
            get
            {
                _DBMySQLMainConnStr = GetAppSetting(@"MySqlMainSrvConnect");
                return KoEnvironment._DBMySQLMainConnStr;
            }
        }

        private static string _PortalOldHostName = "http://portal.korablik.local/";
        public static string PortalOldHostName
        {
            get { return KoEnvironment._PortalOldHostName; }
        }
        public static string PortalOldUrl
        {
            get
            {
                return string.Format(@"http://{0}/", KoEnvironment._PortalOldHostName);
            }
        }
        private static string _PortalHostName = "http://sp.korablik.local";
        public static string PortalHostName
        {
            get { return KoEnvironment._PortalHostName; }
        }
        public static string PortalUrl
        {
            get
            {
                return string.Format(@"http://{0}/", KoEnvironment._PortalHostName);
            }
        }

        public static string WebServiceUrl
        {
            get { return @"http://sp.korablik.local:88/"; }
        }
        #endregion Members
        #region App Settings
        static public string GetAppSetting(String mName)
        {
            String vStr = null;
            SPWebService mSer = SPWebService.ContentService;
            #region Ver 1
            if (mSer != null)
            {
                foreach (SPWebConfigModification mMod in mSer.WebConfigModifications)
                {
                    if (mMod.Owner == mName)
                        vStr = mMod.Value;
                }
            }
            if (vStr != null)
            {
                vStr =
                    vStr.Substring(
                        vStr.IndexOf("value=") + 7
                        , vStr.Length - 7 - vStr.IndexOf("value=") - 4);
            }
            #endregion Ver 1
            else
            #region Ver 2
            {
                string strPath =
@"C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(strPath);
                XmlNode node = xmlDoc.SelectSingleNode(@"/configuration/appSettings");
                foreach (XmlNode keynode in node.ChildNodes)
                {
                    string keyStr = keynode.Attributes["key"].Value;
                    if (keyStr == mName)
                    {
                        vStr = keynode.Attributes["value"].Value;
                        break;
                    }
                }
            }
            #endregion Ver 2
            if (String.IsNullOrEmpty(vStr))
                vStr = "";
            return vStr;
        }
        #endregion App Settings
        #region Web Settings
        public static Exception GetWebSetting(ref string parRet, string parTitle, string parKey, string parSubKey)
        {
            Exception ret = null;
            if (string.IsNullOrEmpty(parRet))
                parRet = string.Empty;
            string s = "";
            string SettingsCamlStr = string.Format(
@"
<Where>
    <And>
        <And>
        <Eq>
            <FieldRef Name='Title' />
            <Value Type='Text'>{0}</Value>
        </Eq>
        <Eq>
            <FieldRef Name='Key' />
            <Value Type='Text'>{1}</Value>
        </Eq>
        </And>
        <Eq>
        <FieldRef Name='SubKey' />
        <Value Type='Text'>{2}</Value>
        </Eq>
    </And>
</Where>
", parTitle, parKey, parSubKey);
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite site = new SPSite("http://localhost"))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList list = web.Lists["Settings"];
                            SPQuery qry = new SPQuery();
                            qry.Query = SettingsCamlStr;
                            qry.RowLimit = 1;
                            foreach (SPListItem item in list.GetItems(qry))
                            {
                                if (item["Title"].ToString() == parTitle
                                    && item["Key"].ToString() == parKey
                                    && item["SubKey"].ToString() == parSubKey)
                                {
                                    s = item["Value"].ToString();
                                    break;
                                }
                            }

                        }
                    }
                }
                catch (Exception ex)
                {
                    ret = new Exception(ex.Message, ex);
                }
            });
            if (ret == null)
                parRet = s;
            return ret;
        }
        public static Exception SetWebSetting(string parTitle, string parKey, string parSubKey, string parNewValue)
        {
            Exception ret = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string SettingsCamlStr = string.Format(
@"
<Where>
    <And>
        <And>
        <Eq>
            <FieldRef Name='Title' />
            <Value Type='Text'>{0}</Value>
        </Eq>
        <Eq>
            <FieldRef Name='Key' />
            <Value Type='Text'>{1}</Value>
        </Eq>
        </And>
        <Eq>
        <FieldRef Name='SubKey' />
        <Value Type='Text'>{2}</Value>
        </Eq>
    </And>
</Where>
", parTitle, parKey, parSubKey);
                try
                {
                    using (SPSite site = new SPSite("http://localhost"))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList list = web.Lists["Settings"];
                            SPQuery qry = new SPQuery();
                            qry.Query = SettingsCamlStr;
                            qry.RowLimit = 1;
                            foreach (SPListItem item in list.GetItems(qry))
                            {
                                if (item["Title"].ToString() == parTitle
                                    && item["Key"].ToString() == parKey
                                    && item["SubKey"].ToString() == parSubKey)
                                {
                                    item["Value"] = parNewValue;
                                    item.SystemUpdate();
                                    item.Update();
                                    break;
                                }
                            }

                        }
                    }
                }
                catch (Exception ex)
                {
                    ret = new Exception(ex.Message, ex);
                }
            });
            return ret;
        }
        public static Exception GetSetting_CreateInDoc_LastSuccessfully(ref DateTime parDT)
        {
            string parStr = string.Empty;
            Exception ret = GetWebSetting(ref parStr
                , "Job-CreateInDocs"
                , "LastSuccessfully"
                , "DateTime");
            if (ret != null)
                return ret;
            try
            {
                parDT = DateTime.Parse(parStr);
            }
            catch (Exception ex)
            {
                ret = new Exception(ex.Message, ex);
            }
            return ret;
        }
        public static Exception SetSetting_CreateInDoc_LastSuccessfully(DateTime parNewDT)
        {
            string parStr = parNewDT.ToString();
            Exception ret = SetWebSetting(
                  "Job-CreateInDocs"
                , "LastSuccessfully"
                , "DateTime"
                , parStr);
            return ret;
        }
        public static Exception GetSetting_Shops_LastSuccessfully(ref DateTime parDT)
        {
            string parStr = string.Empty;
            Exception ret = GetWebSetting(ref parStr
                , "Job-CreateShops"
                , "LastSuccessfully"
                , "DateTime");
            if (ret != null)
                return ret;
            try
            {
                parDT = DateTime.Parse(parStr);
            }
            catch (Exception ex)
            {
                ret = new Exception(ex.Message, ex);
            }
            return ret;
        }
        public static Exception SetSetting_Shops_LastSuccessfully(DateTime parNewDT)
        {
            string parStr = parNewDT.ToString();
            Exception ret = SetWebSetting(
                  "Job-CreateShops"
                , "LastSuccessfully"
                , "DateTime"
                , parStr);
            return ret;
        }
        public static Exception GetSetting_Suplier_LastSuccessfully(ref DateTime parDT)
        {
            string parStr = string.Empty;
            Exception ret = GetWebSetting(ref parStr
                , "Job-CreateSuplier"
                , "LastSuccessfully"
                , "DateTime");
            if (ret != null)
                return ret;
            try
            {
                parDT = DateTime.Parse(parStr);
            }
            catch (Exception ex)
            {
                ret = new Exception(ex.Message, ex);
            }
            return ret;
        }
        public static Exception SetSetting_Suplier_LastSuccessfully(DateTime parNewDT)
        {
            string parStr = parNewDT.ToString();
            Exception ret = SetWebSetting(
                  "Job-CreateSuplier"
                , "LastSuccessfully"
                , "DateTime"
                , parStr);
            return ret;
        }
        #endregion Web Settings
        #region Logs
        public static Exception Log_Add(string parName, string parKey, string parSubKey, string parValue)
        {
            Exception ret = DBSPLog.Insert(parName, parKey, parSubKey, parValue);
            return ret;
        }
        public static Exception Log_Add(string parName, string parKey, string parSubKey, string parValue
            , string parMsg, int parErrId, int parWarningLevel, int parRetCode, int parCountInfo)
        {
            Exception ret = DBSPLog.Insert(parName, parKey, parSubKey, parValue
                , parMsg, parErrId, parWarningLevel, parRetCode, parCountInfo);
            return ret;
        }
        #endregion Logs
    }
}
